/*
 * ESP32葡萄病虫害监控传感器系统
 * 
 * 功能：
 * 1. 监测环境参数：温湿度、土壤湿度、光照强度、空气质量
 * 2. 图像识别：葡萄叶片病虫害识别
 * 3. 数据传输：WiFi连接与数据上传
 * 4. 预警功能：环境参数异常预警和病虫害风险预警
 */

#include <WiFi.h>
#include <PubSubClient.h>
#include <DHT.h>
#include <Wire.h>
#include <Adafruit_SSD1306.h>
#include <BH1750.h>
#include <Adafruit_CCS811.h>

// 网络配置
const char* ssid = "your_wifi_ssid";
const char* password = "your_wifi_password";
const char* mqtt_server = "your_mqtt_server";

// 传感器引脚定义
#define DHT_PIN 4
#define DHT_TYPE DHT22
#define SOIL_MOISTURE_PIN 34
#define BUZZER_PIN 18

// 传感器对象
DHT dht(DHT_PIN, DHT_TYPE);
BH1750 lightMeter;
Adafruit_CCS811 ccs;
Adafruit_SSD1306 display(128, 64, &Wire, -1);

// WiFi和MQTT客户端
WiFiClient espClient;
PubSubClient client(espClient);

// 传感器数据变量
float temperature = 0.0;
float humidity = 0.0;
int soilMoisture = 0;
uint16_t lightIntensity = 0;
float co2Level = 0.0;

// 阈值设置
const float TEMP_THRESHOLD_HIGH = 35.0;
const float TEMP_THRESHOLD_LOW = 10.0;
const float HUMIDITY_THRESHOLD_HIGH = 80.0;
const float HUMIDITY_THRESHOLD_LOW = 40.0;
const int SOIL_MOISTURE_THRESHOLD_LOW = 300;
const uint16_t LIGHT_THRESHOLD_LOW = 1000;
const float CO2_THRESHOLD_HIGH = 1200.0;

void setup() {
  Serial.begin(115200);
  
  // 初始化传感器
  dht.begin();
  lightMeter.begin();
  if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
    Serial.println(F("SSD1306 allocation failed"));
  }
  
  if(!ccs.begin()){
    Serial.println("Failed to start CCS811 sensor! Please check your wiring.");
  }
  
  // 初始化引脚
  pinMode(BUZZER_PIN, OUTPUT);
  digitalWrite(BUZZER_PIN, LOW);
  
  // 连接WiFi
  setup_wifi();
  
  // 连接MQTT服务器
  client.setServer(mqtt_server, 1883);
  
  // 显示启动信息
  display.clearDisplay();
  display.setTextSize(1);
  display.setTextColor(SSD1306_WHITE);
  display.setCursor(0, 0);
  display.println("Grape Monitor");
  display.println("System Starting...");
  display.display();
  delay(2000);
}

void setup_wifi() {
  delay(10);
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void reconnect() {
  // 循环直到重新连接
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // 创建一个随机的客户端ID
    String clientId = "ESP32Client-";
    clientId += String(random(0xffff), HEX);
    
    // 尝试连接
    if (client.connect(clientId.c_str())) {
      Serial.println("connected");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // 等待5秒后重试
      delay(5000);
    }
  }
}

void readSensors() {
  // 读取温湿度传感器
  temperature = dht.readTemperature();
  humidity = dht.readHumidity();
  
  // 读取土壤湿度传感器
  soilMoisture = analogRead(SOIL_MOISTURE_PIN);
  
  // 读取光照传感器
  lightIntensity = lightMeter.readLightLevel();
  
  // 读取空气质量传感器
  if(ccs.available()){
    if(!ccs.readData()){
      co2Level = ccs.geteCO2();
    }
  }
}

void displayData() {
  display.clearDisplay();
  display.setCursor(0, 0);
  display.print("Temp: ");
  display.print(temperature);
  display.println(" C");
  
  display.print("Humidity: ");
  display.print(humidity);
  display.println(" %");
  
  display.print("Soil: ");
  display.println(soilMoisture);
  
  display.print("Light: ");
  display.print(lightIntensity);
  display.println(" lx");
  
  display.print("CO2: ");
  display.print(co2Level);
  display.println(" ppm");
  
  display.display();
}

void checkAlerts() {
  bool alert = false;
  
  // 检查温度异常
  if (temperature > TEMP_THRESHOLD_HIGH || temperature < TEMP_THRESHOLD_LOW) {
    alert = true;
  }
  
  // 检查湿度异常
  if (humidity > HUMIDITY_THRESHOLD_HIGH || humidity < HUMIDITY_THRESHOLD_LOW) {
    alert = true;
  }
  
  // 检查土壤湿度过低
  if (soilMoisture < SOIL_MOISTURE_THRESHOLD_LOW) {
    alert = true;
  }
  
  // 检查光照过低
  if (lightIntensity < LIGHT_THRESHOLD_LOW) {
    alert = true;
  }
  
  // 检查CO2浓度过高
  if (co2Level > CO2_THRESHOLD_HIGH) {
    alert = true;
  }
  
  // 如果有异常，触发警报
  if (alert) {
    digitalWrite(BUZZER_PIN, HIGH);
    delay(1000);
    digitalWrite(BUZZER_PIN, LOW);
  }
}

void sendData() {
  // 发送数据到MQTT服务器
  if (!client.connected()) {
    reconnect();
  }
  client.loop();
  
  // 发送传感器数据
  String data = "{\"temperature\":"+String(temperature)+
                ",\"humidity\":"+String(humidity)+
                ",\"soilMoisture\":"+String(soilMoisture)+
                ",\"lightIntensity\":"+String(lightIntensity)+
                ",\"co2Level\":"+String(co2Level)+"}";
                
  client.publish("grape_monitor/sensors", data.c_str());
}

void loop() {
  // 读取所有传感器数据
  readSensors();
  
  // 显示数据
  displayData();
  
  // 检查警报条件
  checkAlerts();
  
  // 发送数据
  sendData();
  
  // 等待5秒后再次读取
  delay(5000);
}